import React, { useState } from "react";

const TaskItem = ({ task, onDelete, onToggle, onEdit }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editText, setEditText] = useState(task.text);

  const handleEdit = () => {
    if (isEditing) {
      onEdit(task.id, editText);
      setIsEditing(false);
    } else {
      setIsEditing(true);
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === "Enter") {
      handleEdit();
    } else if (e.key === "Escape") {
      setEditText(task.text);
      setIsEditing(false);
    }
  };

  return (
    <div
      className={`list-group-item d-flex align-items-center ${
        task.completed ? "bg-light" : ""
      }`}
    >
      <div className="form-check me-3">
        <input
          className="form-check-input"
          type="checkbox"
          checked={task.completed}
          onChange={() => onToggle(task.id)}
          id={`task-${task.id}`}
        />
        <label className="form-check-label" htmlFor={`task-${task.id}`}></label>
      </div>

      <div className="flex-grow-1 me-3">
        {isEditing ? (
          <input
            type="text"
            className="form-control form-control-sm"
            value={editText}
            onChange={(e) => setEditText(e.target.value)}
            onKeyDown={handleKeyPress}
            onBlur={handleEdit}
            autoFocus
          />
        ) : (
          <span
            className={`task-text ${
              task.completed ? "text-decoration-line-through text-muted" : ""
            }`}
            onDoubleClick={() => setIsEditing(true)}
            style={{ cursor: "pointer" }}
          >
            {task.text}
          </span>
        )}
      </div>

      <div className="btn-group btn-group-sm">
        <button
          className="btn btn-outline-primary"
          onClick={handleEdit}
          title={isEditing ? "保存" : "编辑"}
        >
          <i className={`bi ${isEditing ? "bi-check" : "bi-pencil"}`}></i>
        </button>
        <button
          className="btn btn-outline-danger"
          onClick={() => onDelete(task.id)}
          title="删除"
        >
          <i className="bi bi-trash"></i>
        </button>
      </div>
    </div>
  );
};

export default TaskItem;
